package com.lzb.musicplayer.utils;


import android.app.Activity;
import android.media.MediaMetadataRetriever;
import android.os.Build;


import com.lzb.musicplayer.audio.AudioPlayerManager;
import com.lzb.musicplayer.bean.GroupMusicInfo;
import com.lzb.musicplayer.bean.MusicFile;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MusicScanner {


    // 辅助方法处理空值
    private static String getMetadata(MediaMetadataRetriever mmr, int key, String defaultValue) {
        String value = mmr.extractMetadata(key);
        return (value != null && !value.isEmpty())  ? value : defaultValue;
    }


    // 2. 核心分组方法
    public static List<GroupMusicInfo> groupByProperty(List<MusicFile> originList, Function<MusicFile, String> keyExtractor) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return originList.stream()
                    .collect(Collectors.groupingBy(keyExtractor))  // 按指定属性分组
                    .entrySet().stream()
                    .map(entry -> new GroupMusicInfo(entry.getKey(),  entry.getValue()))
                    .collect(Collectors.toList());
        }else {
            List<GroupMusicInfo> groupByProperty=new ArrayList<>();
            groupByProperty.add( new GroupMusicInfo("1",originList));
            return groupByProperty;
        }

    }
    public static List<GroupMusicInfo> groupByProperty(Activity activity,List<MusicFile> originList) {
        List<GroupMusicInfo>list=new ArrayList<>();
        boolean isHas=false;
        for (int i = 0; i < originList.size(); i++) {
            List<MusicFile> musicFileList = new ArrayList<>();
            MusicFile musicFile = originList.get(i);
            musicFile.setGroupKey(i+"");
            musicFileList.add(musicFile);
            GroupMusicInfo groupMusicInfo = new GroupMusicInfo(i+"", musicFileList);
            if (AudioPlayerManager.getInstance(activity).getCurrentTrack()!=null&&AudioPlayerManager.getInstance(activity).getCurrentTrack().getPath().equals(musicFile.getPath())
                    &&AudioPlayerManager.getInstance(activity).isPlaying()==true&&!isHas){
                groupMusicInfo.setPlay(true);
                isHas=true;
            }else {
                groupMusicInfo.setPlay(false);
            }

            list.add(groupMusicInfo);
        }
        return list;

    }

    public static boolean listUtils(List<MusicFile> list,List<MusicFile> list1) {
        boolean type=false;
        if (list.size()==list1.size()){
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getPath().equals(list1.get(i).getPath())){
                    type=true;
                }else {
                    type=false;
                }
            }
        }
        return type;

    }
}